<script>
import axios from 'axios';

export default {
  data() {
    return {
      productName: '',
      category: '',
      stock: 1,
      price: 0.1,
      status: 'on',
      imageFile: null,
      imageUrl: '',
      loading: false,
      error: ''
    };
  },
  methods: {
    async addProduct() {
      const token = localStorage.getItem('merchantInfo') ? JSON.parse(localStorage.getItem('merchantInfo')).token : null;

      if (!token) {
        this.error = '请先登录';
        return;
      }

      const formData = new FormData();
      formData.append('productName', this.productName);
      formData.append('category', this.category);
      formData.append('stock', this.stock);
      formData.append('price', this.price);
      formData.append('status', this.status);

      if (this.imageFile) {
        formData.append('image', this.imageFile);
      }

      this.loading = true;
      this.error = '';

      try {
        const response = await axios.post(
          '/api/merchant/addProductsWithImages',
          formData,
          {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'multipart/form-data'
            }
          }
        );

        if (response.data.success) {
          alert('商品添加成功！');
          // 重置表单
          this.resetForm();
        } else {
          this.error = response.data.message || '添加失败';
        }
      } catch (error) {
        console.error('添加商品失败:', error);
        this.error = '网络错误，请检查网络连接或联系管理员';
      } finally {
        this.loading = false;
      }
    },

    resetForm() {
      this.productName = '';
      this.category = '';
      this.stock = 1;
      this.price = 0.1;
      this.status = 'on';
      this.imageFile = null;
      this.imageUrl = '';
    },

    onImageChange(event) {
      const file = event.target.files[0];
      if (file) {
        this.imageFile = file;
        this.imageUrl = URL.createObjectURL(file);
      }
    }
  }
};
</script>